/**
 * BJ-DEMO Upload with ngDialog
 * Designed by vicco
 * 2015-10-09
 */
(function(){
    'use strict';
/**
 * 全局通用服务
 * 服务依赖通知模块组件
 */
angular.module('uploadModule', ['ngDialog']);

/**
 * 全局通用上传服务
 */
angular.module('uploadModule').factory('uploadService',uploadService);
/**
 * 全局上传文件指令
 */
angular.module("uploadModule").directive("dropZone",dropZone);

angular.module("uploadModule").controller('uploadFileController',uploadFileController);

/**
 * 手动依赖注入相关内容
 * @type {string[]}
 */
uploadService.$inject = ['ngDialog'];
uploadFileController.$inject =['$scope'];

/**
 * 上传服务只对全局通用的上传模态框进行一次封装，以便在任何地方调用
 * 直接返回promise对象
 *
 * @param ngDialog
 * @returns {{}} promise obj
 */
function uploadService(ngDialog) {
    var service = {};

    service.upload = function (config) {
        var dialog = ngDialog.open({
            templateUrl: "templates/uploadFiles.html",
            controller: 'uploadFileController',
            data : config
        });

        return dialog.closePromise;

    };

    return service;
}

/**
 * 全局通用上传文件指令方法
 * @returns {{restrict: string, link: Function}}
 */
function dropZone(){
    return {
        restrict: 'AE',
        link: function(scope, element, attrs) {

            var options = scope.uploadConfig;

            var config = {
                url: '/BusDeviceMonitor/TemEmhistorystatCtr/readExcel',
                maxFilesize: 0.5,
                paramName: "uploadfile",
                //maxThumbnailFilesize: 1,
                //parallelUploads: 1,
                thumbnailWidth : 520,
                maxFiles : 20,
                autoProcessQueue: false,
                addRemoveLinks: true,
                acceptedFiles : '.jpg,.png,.gif',
                dictRemoveFile : '',
                dictCancelUpload: '',
                dictInvalidFileType : '不支持上传此格式的文件',
                dictCancelUploadConfirmation : '确认要终止该文件上传吗?',
                dictFileTooBig :'您上传的文件容量过大，最大支持{{maxFilesize}}MB',
                dictDefaultMessage : "单击或者将文件拖动到这里",
                dictMaxFilesExceeded : "您无法再上传更多的文件了"
            };

            var finalConfig = angular.extend(config, options);
            
            console.log( finalConfig );

            /**
             * 用来在上传组件中展示一些配置属性，告知用户。例如最大支持多少MB的文件，支持什么格式的，支持上传多少文件等
             * @type {{maxFilesize: (number|c.defaultOptions.maxFilesize)}}
             */
            scope.modalConfig = {
                maxFilesize     : finalConfig.maxFilesize,
                acceptedFiles   : finalConfig.acceptedFiles,
                maxFiles        : finalConfig.maxFiles
            };

            var eventHandlers = {
                'addedfile': function(file) {
                    scope.$apply(function(){
                        scope.fileUpLoadDisabled = false;
                    })
                },
                'removedfile':function(file){
                    scope.$apply(function(){
                        if( dropzone.getQueuedFiles().length ){
                            scope.fileUpLoadDisabled = false;
                        } else {
                            scope.fileUpLoadDisabled = true;
                        }
                    })
                },
                'success': function (file, response) {

                    scope.$apply(function(){

                        var successFile = {
                            file : file,
                            res  : response
                        };

                        scope.uploadSuccess.push(successFile);
                        scope.fileUploaded = true;

                        if( dropzone.getQueuedFiles().length ){
                            scope.fileUpLoadDisabled = false;
                        } else {
                            scope.fileUpLoadDisabled = true;
                        }

                    });
                },
                'error' : function(errorMessage){
                    scope.$apply(function(){
                        scope.uploadFailed = errorMessage;
                        scope.fileUploaded = false;
                    })
                }

            };

            var dropzone = new Dropzone(element[0], finalConfig);


            angular.forEach(eventHandlers, function(handler, event) {
                dropzone.on(event, handler);
            });

            scope.processDropzone = function() {
                dropzone.processQueue();
            };

            scope.resetDropzone = function() {
                dropzone.removeAllFiles();
            }
        }
    }
};

/**
 * 全局通用上传组件模态框控制器
 * uploadFiles fn  负责将队列上传
 * uploadConfig obj  用户自定义的上传属性，例如修改上传最大SIZE，支持的上传类型等等，
 * 在指令中接收到后会通过angular.extend合并之前的属性，并赋给dropzone对象。
 * fileUpLoadDisabled  控制上传按钮，当无任何上传队列或者已上传完毕，将不能再点击上传按钮
 * fileUploaded 控制完成按钮，成功后才能点击
 * uploadSuccess obj  上传成功后返回的response,这是一个object对象
 * uploadFailed obj 上传失败后返回的内容
 *
 * 以上对象和属性与Directive中进行绑定
 *
 * @param $scope
 */
function uploadFileController($scope){

    $scope.uploadFiles = function(){
        $scope.processDropzone();
    };

    $scope.uploadConfig = $scope.ngDialogData;

    $scope.fileUpLoadDisabled = true;

    $scope.fileUploaded = false;

    $scope.uploadSuccess = [];

    $scope.uploadFailed = "";

}

angular.module("uploadModule").run(["$templateCache", function($templateCache){
    $templateCache.put("templates/uploadFiles.html",
        "<div class=\"modal-header\">" +
        "<h4 class=\"modal-title\" id=\"myModalLabel\"><span class=\"glyphicon glyphicon-cloud upload-modal-title-img\"></span>文件上传管理器</h4>" +
        "</div>" +
        "<div class=\"modal-body\">" +
        "      <form action=\"\" class=\"dropzone\" drop-zone=\"\" id=\"dropzone\"></form>" +
        "</div>" +
        "<div class=\"modal-footer\">" +
        "     <span class=\"upload-modal-text\">" +
        "           <span class=\"glyphicon glyphicon-info-sign\"></span>" +
        "           容量支持:{{ modalConfig.maxFilesize}}MB( {{ modalConfig.maxFilesize * 1000 }}KB ), 文件格式:{{ modalConfig.acceptedFiles}}, 上传数量:{{modalConfig.maxFiles }}个" +
        "     </span>" +
        /*"      <button type=\"submit\" class=\"btn btn-primary\" ng-disabled=\"fileUpLoadDisabled\" ng-click=\"uploadFiles()\"></button>" +*/
        "      <button type=\"button\" class=\"btn btn-success\" ng-disabled=\"!fileUploaded\" ng-click=\"closeThisDialog(uploadSuccess);\">完成</button>" +
        "</div>"
    );
}]);

})()